﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Xml;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml.Linq;
using CharitiesLib;
using System.Drawing.Imaging;

namespace Charities
{
    public partial class MainSettings : Form
    {
        Form fo = null;
        public MainSettings(Form md)
        {
            fo = md;
            MdiParent = md;
            InitializeComponent();
        }
        public bool is_loaded = false;
        OpenFileDialog ofp = new OpenFileDialog();
        ModelContainer ctx = new ModelContainer();
        CharityInfo info = null;


        private void MainSettings_Load(object sender, EventArgs e)
        {
            // add this form to window list
            ((Forms.FormMDI)fo).addFormToWindowsList(this);
            is_loaded = true;
            try
            {
                if (ctx.CharityInfos.Count() > 0)
                {
                    info = ctx.CharityInfos.First();
                    txb_CharityName.Text = info.CharityName;
                    txbAddress.Text = info.Address;
                    if (info.AuthorisationDate != null)
                    {
                        string[] datearr = info.AuthorisationDate.Split('/');
                        if (datearr.Count() == 3)
                        {
                            txbDay.Text = datearr[0];
                            txbmonth.Text = datearr[1];
                            txbyear.Text = datearr[2];
                        }
                        else
                        {
                            txbyear.Text = datearr[0];
                        }
                    }
                    txb_Auth_Number.Text = info.LicencesNumber;
                    txbBankAccount.Text = info.BankAccountNumber;
                    txbBankName.Text = info.BankName;
                    txbBankAccount2.Text = info.SecondBankAccountNumber;
                    txbBankName2.Text = info.SecondBankName;
                    txb_PhoneNumbers.Text = info.PhoneNumber;
                    txb2ndPhoneNumber.Text = info.SecondPhoneNumber;
                    txbEmail.Text = info.Email;
                    if (info.Logo != null)
                    {
                        ReadtoPictureBox(info.Logo);
                    }
                }
                else
                {
                    info = new CharityInfo();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }
        }

        private void btn_save_Click(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(txb_CharityName.Text))
                {

                    info.CharityName = txb_CharityName.Text;
                    info.Address = txbAddress.Text;
                    
                    if (!string.IsNullOrWhiteSpace(txbyear.Text) && !string.IsNullOrWhiteSpace(txbmonth.Text) && !string.IsNullOrWhiteSpace(txbDay.Text))
                        info.AuthorisationDate = string.Format("{0}/{1}/{2}", txbDay.Text, txbmonth.Text, txbyear.Text);
                    else
                        info.AuthorisationDate = string.Format("{0}", txbyear.Text);

                    info.LicencesNumber = txb_Auth_Number.Text.Trim().Length > 0 ? txb_Auth_Number.Text.Trim() : null;
                    info.BankAccountNumber = txbBankAccount.Text.Trim().Length > 0 ? txbBankAccount.Text.Trim() : null;
                    info.BankName = txbBankName.Text.Trim().Length > 0 ? txbBankName.Text.Trim() : null;
                    info.SecondBankAccountNumber = txbBankAccount2.Text.Trim().Length > 0 ? txbBankAccount2.Text.Trim() : null;
                    info.SecondBankName = txbBankName2.Text.Trim().Length > 0 ? txbBankName2.Text.Trim() : null;
                    info.PhoneNumber = txb_PhoneNumbers.Text.Trim().Length > 0 ? txb_PhoneNumbers.Text.Trim() : null;
                    info.SecondPhoneNumber = txb2ndPhoneNumber.Text.Trim().Length > 0 ? txb2ndPhoneNumber.Text : null;
                    info.Email = txbEmail.Text.Trim().Length > 0 ? txbEmail.Text.Trim() : null;
                    info.Logo = pBoxLogo.Image != null ? GetImageFromPicBox() : null;
                    if (ctx.CharityInfos.Count() > 0)
                    {
                        ctx.SaveChanges();
                    }
                    else
                    {
                        ctx.CharityInfos.Add(info);
                        ctx.SaveChanges();
                    }
                    MessageBox.Show("تم الحفظ بنجاح","تم الحفظ",MessageBoxButtons.OK,MessageBoxIcon.Information);
                }

            }
            catch(Exception exx)
            {
                MessageBox.Show(" خطأ في الحفظ: "+exx.Message,"error",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }

        }

        private void btn_dispose_Click(object sender, EventArgs e)
        {
            this.Close();
            is_loaded = false;
        }
        private void btn_browse_Click(object sender, EventArgs e)
        {
            ofp.Filter = "JPG File|*.jpg|PNG File|*.png";
            if (ofp.ShowDialog() == DialogResult.OK)
            {
                string path = ofp.FileName;
                pBoxLogo.Load(path);
            }
        }

        private void MainSettings_FormClosed(object sender, FormClosedEventArgs e)
        {
            is_loaded = false;
            // remove this form from windows list
            ((Forms.FormMDI)fo).removeFormFromWindowsList(this);
        }

        private void MainSettings_Activated(object sender, EventArgs e)
        {
            // activate this form and add it windows list as activate one
            ((Forms.FormMDI)this.MdiParent).activateWindow(this);
        }

        //Open file into a filestream and 
        //read data in a byte array.
        private byte[] GetImageFromPicBox()
        {
            MemoryStream stream = new MemoryStream();
            //handle Write permissions
            using (Bitmap tempImage = new Bitmap(pBoxLogo.Image))
            {
                if (ofp.FilterIndex == 0)
                {
                    tempImage.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                else if (ofp.FilterIndex == 1)
                {
                    tempImage.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                }
                else
                {
                    tempImage.Save(stream, ImageFormat.Gif);
                }
            } 

            byte[] pic = stream.ToArray();
            return pic;
        }
        private void ReadtoPictureBox(byte[] pic)
        {
            MemoryStream stream = new MemoryStream(pic);
            pBoxLogo.Image = Image.FromStream(stream);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            DialogResult res = MessageBox.Show("هل أنت متأكد من حذف الاعدادات؟ عدم وجود إعدادات قد يؤدي إلى أخطاء في تنسيق التقارير","تأكيد حذف الاعدادات",MessageBoxButtons.YesNo,MessageBoxIcon.Warning);
            if (res == DialogResult.Yes)
            {
                ctx.CharityInfos.Remove(info);
                ctx.SaveChanges();
                Action<Control.ControlCollection> func = null;

                func = (controls) =>
                {
                    foreach (Control control in controls)
                        if (control is TextBox)
                            (control as TextBox).Clear();
                        else
                            func(control.Controls);
                };
                pBoxLogo.Image = null;
                func(Controls);
            }

        }


    }
}
